<?php

namespace App\Jobs\activity;

use App\Common\RedisCache\YearActivityCache;
use App\Jobs\Job;
use App\services\v1\LuckServices;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;

class YearActivityCommand extends Job
{
    const QUEUE_NAME = 'YearActivitySendCouponSubscribe:{laterQueue}';
    private $data;
    public  $describe;
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * @return void
     */
    public function handle()
    {
        Log::info($this->describe.'看门狗收到数据-', $this->data);
        $laterRedisParamKey = $this->data['laterRedisKey'];//看门狗锁
        $redisParamKey      = $this->data['redisKey'];//抽奖锁
        $startMillisecond   = $this->data['redisValue'];//抽奖锁redis值
        $this->describe     = $this->data['describe'];//描述
        $yearActivityCache  = new YearActivityCache();
        //没有看门狗锁 不用重试
        $yearActivityCache->setKeyParameter($laterRedisParamKey);
        $exists = $yearActivityCache->exists();
        if (!$exists) {
            Log::info($this->describe.$yearActivityCache->getKey().' 活动抽奖锁正常');
            return;
        }
        //重新获取锁
        $yearActivityCache->setKeyParameter($redisParamKey);
        $setNxRes = $yearActivityCache->set($startMillisecond, ['nx','ex' => $yearActivityCache->expire]);
        Log::info($this->describe.$yearActivityCache->getKey().' 活动抽奖锁续命');
        //限制门狗查看10次
        $yearActivityCache->setKeyParameter(array_merge($laterRedisParamKey,['counter']));
        $counter = (int)$yearActivityCache->get();
        //看门狗查看次数加1
        $counter++;
        $yearActivityCache->set($counter,30);
        if ($counter > 10) {
            Log::info($this->describe.$yearActivityCache->getKey().' 活动抽奖看门狗看了{'.$counter.'}次，放弃处理');
            return;
        }
        //看门狗每2秒重试抽奖锁
        Queue::later($yearActivityCache->expire-2
            , new YearActivityCommand(['redisKey' => $redisParamKey,'redisValue' => $startMillisecond, 'laterRedisKey' => $laterRedisParamKey, 'describe' => $this->describe])
            ,''
            ,YearActivityCommand::QUEUE_NAME
        );

        Log::info($this->describe.$yearActivityCache->getKey().' 活动抽奖看门狗看了{'.$counter.'}次');
    }
}